/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [Example_04_Thread_Clock_V1.java]
 * Creation Date        [04-Jul-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_08_thread;

import java.util.Calendar;

import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 * 线程时钟 - 使用thread.sleep
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Example_04_Thread_Clock_V1 {

	public static void initClock() {
		JFrame frame = new JFrame("我的时钟");
		JLabel clock = new JLabel("clock");
		clock.setHorizontalAlignment(JLabel.CENTER);
		frame.add(clock, "Center");
		frame.setSize(240, 80);
		frame.setLocation(300, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);

		while (true) {
			clock.setText(getTime());
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		Example_04_Thread_Clock_V1.initClock();
	}

	private static String getTime() {
		Calendar calendar = Calendar.getInstance();
		String time = calendar.get(Calendar.YEAR) + "年"
				+ (calendar.get(Calendar.MONTH) + 1) + "月"
				+ calendar.get(Calendar.DATE) + "日 ";

		int h = calendar.get(Calendar.HOUR_OF_DAY);
		int m = calendar.get(Calendar.MINUTE);
		int s = calendar.get(Calendar.SECOND);

		String ph = h < 10 ? "0" : "";
		String pm = m < 10 ? "0" : "";
		String ps = s < 10 ? "0" : "";
		return time + ph + h + "时" + pm + m + "分" + ps + s + "秒";
	}
}
